class: left, middle, inverse, title-slide # II Congreso - Escuela en Estadística espacial ## Visualización de datos geoespaciales en R ###
Pablo Paccioretti
Cecilia Bruno
Facultad de Ciencias Agropecuaras - UNC - CONICET
--- ## Temas 1. Introducción a R 1. Manejo de datos espaciales con `sf` + Lectura de archivos de diferentes formatos - Shapefile - Base de datos de texto (*data frame*) + Manejo de objetos `sf` + Proyección y reproyección 1. Visualización para comunicación de resultados + Paquete `ggplot2` + Paquete `tmap` 1. Visualización interactiva + Paquete `leaflet` --- class: inverse, middle, center #
# .fancy[Esta presentación y los datos están disponibles en] --- ## Generalidades de
- [R](https://cran.r-project.org/) (R Core Team, 2019) es un lenguaje de programación orientado a objetos. - Creado por Ross Ihaka y Robert Gentleman en 1993 como un dialecto del software S. - Puede ser instalado en múltiples plataformas. - [RStudio](https://www.rstudio.com/products/rstudio/download/#download) (RStudio Team, 2016) es un entorno de desarrollo integrado (*Integrated Development Environment* IDE) que facilita la programación. - R permite realizar estadísticas geoespaciales, modelado y visualización con paquetes especializados. --- ## Interfaz de RStudio <img src="images/Rstudiopartes.jpg" width="80%" style="display: block; margin: auto;" /> --- ## Sintaxis + Los `#` indican comentarios en el código, todo lo que está a la derecha de este símbolo no será ejecutado. + Si deseamos guardar un resultado de una función en un objeto, debemos utilizar la función de asignación `<-`. + Argumentos de una functión se especifican entre paréntesis y están separados por coma: `NombreFuncion(arg1, arg2)`. + R distingue mayúsculas y minúsculas. + Caracteres especiales (espacios, tildes, signos) son reemplazados por . en nombres de columnas. + Se recomienda evitar el uso de tildes, ñ, símbolos matemáticos para nombres de los niveles de factores, columnas y objetos. --- ## Ejemplo de código ```r 2+2 ``` ``` ## [1] 4 ``` ```r normalAleatorio <- rnorm(10, mean = 0, sd = 1) normalAleatorio ``` ``` ## [1] 0.16823179 -1.49866116 -1.28157213 -1.80084337 -2.28924654 0.08858701 ## [7] 1.26016048 0.27558302 -1.30248539 -1.19878180 ``` --- <!-- layout: false --> class: inverse, middle, center # Datos espaciales --- # R-espacial - Hay numerosos paquetes para el manejo de datos espaciales `geoR`, `sp`, `gstat`, `rgdal`, `spdep`, `sf`, `stars`, `raster`, entre otros. - Los primeros procedimientos espaciales de R se originaron en el lenguaje S, en la década del 90 (Bivand and Gebhardt, 2000). - A partir del 2000, R ofrece paquetes que posibilitan el tratamiento de datos espaciales a través de diversos métodos. Algunos de ellos todavía se utilizan. - El paquete `sf` se basa en su predecesor `sp`. --- # Datos espaciales en R + Los datos vectoriales, usando puntos, líneas y polígonos, permiten representar superficies
+ Los datos tipo *raster* divide la superficie en celdas (pixeles) de tamaño constante > En este curso utilizaremos: > - Paquete `sf` para trabajar con archivos vectoriales > - Paquete `raster` para trabajar con *rasters*  --- <img src="images/Satelite.jpg" width="10%" style="display: block; margin: auto;" /><img src="images/SateliteTrabajando.gif" width="10%" style="display: block; margin: auto;" /> --- # Paquete `sf` *Simple features* es una manera estandarizada de codificar, en computadoras, datos **vectoriales** (puntos, lineas y polígonos)
El paquete `sf` implementa *simple features* en R y conserva las mismas capacidades para el manejo de datos vectoriales como los paquetes `sp`, `rgeos` y `rgdal` (Pebesma, 2018) --- # Paquete `sf` - El paquete `sf` permite el análisis y el manejo de archivos con datos espaciales -- - Los objetos espaciales `sf` están almacenados como `data.frame`, donde los datos geográficos ocupan una columna especial (*geometry list-column*) -- - A partir de un objeto `sf` se puede obtener un `data.frame`, el cual tendrá una columna del tipo lista con la posición geográfica -- - Las funciones del paquete comienzan con `st_` -- - Los objetos espaciales `sf` pueden ser tratados como `data.frame` en la mayoría de las operaciones ??? - Tipos de objetos espaciales (Vectorial, Raster) - Lectura de diferentes tipos de archivos - Asignación del sistema de coordenadas + Transformacion de cordenadas - Separar las coordenadas de los datos - Recortar capas en función de otra - Herramientas para el manejo de objetos + Media, mediana de valores de punto dentro de poligono + Conteo de puntos dentro de un poligono + Union puntos, union diferentes capas --- # Paquete `raster` - Es compatible con objetos de tipo *raster* en R - Provee numerosas funciones para crear, leer, exportar, manipular y procesar datos de tipo *raster* - Permite trabajar con *raster* de dimensiones muy grandes para ser almacenados en la memoria RAM - Cada celda del archivo *raster*, puede contener un único valor (numérico o categórico) - Se pueden agrupar más de una capa en un mismo *raster* ??? En vez de cargar todo el *raster* en la memoria RAM, tiene la posibilidad de dividirlo en fragmentos más pequeños y procesarlos de manera iterativa. --- # Sistemas de referencia de coordenadas - Define cómo los elementos espaciales de los datos se relacionan con la superficie terrestre - Pueden ser + Sistemas de coordenadas geográficas: Identifica cualquier punto de la superficie terrestre utilizando dos valores: Latitud y Longitud (*lat long*) -- + Proyecciones de sistemas de coordenadas de referencia: Basados en coordenadas Cartesianas en una superficie plana (*UTM*) --- layout: false class: inverse, middle, center # Manos a la obra ##
--- # Lectura de archivos + Vectoriales - shp (departamentos y cuencas de la Provincia de Córdoba) - desde archivo de texto (Muestreo de Suelo de la Provincia) + Raster - tif (DEM) .center[
] --- # Vectoriales ```r head(departamentos <- read_sf("datos/deptos_cba", stringsAsFactors = TRUE), 3) ``` ``` *## Simple feature collection with 3 features and 5 fields *## geometry type: POLYGON ## dimension: XY ## bbox: xmin: -64.29896 ymin: -34.54652 xmax: -62.55098 ymax: -31.93594 ## epsg (SRID): 4326 *## proj4string: +proj=longlat +datum=WGS84 +no_defs ## # A tibble: 3 x 6 ## objectid departa cabecer provincia fuente geometry *## <dbl> <fct> <fct> <fct> <fct> <POLYGON [°]> ## 1 393 PRESIDENT~ LABOULA~ CORDOBA CATAST~ ((-62.8198 -33.89651, -62.8137~ ## 2 341 TERCERO A~ OLIVA CORDOBA CATAST~ ((-63.11768 -32.00111, -63.124~ ## 3 342 JUAREZ CE~ LA CARL~ CORDOBA CATAST~ ((-63.55538 -32.83089, -63.523~ ``` --- ```r summary(departamentos) ``` ``` ## objectid departa cabecer provincia ## Min. :322.0 CALAMUCHITA : 1 ALTA GRACIA : 1 CORDOBA:26 ## 1st Qu.:328.2 CAPITAL : 1 BEL VILLE : 1 ## Median :334.5 COLON : 1 CORDOBA : 1 ## Mean :342.9 CRUZ DEL EJE : 1 COSQUIN : 1 ## 3rd Qu.:340.8 GENERAL ROCA : 1 CRUZ DEL EJE: 1 ## Max. :433.0 GENERAL SAN MARTIN: 1 DEAN FUNES : 1 ## (Other) :20 (Other) :20 ## fuente geometry ## CATASTRO CORDOBA:26 POLYGON :26 ## epsg:4326 : 0 ## +proj=long...: 0 ## ## ## ## ``` --- <!-- # Visualicemos la capa --> ```r plot(departamentos) ``` <img src="index_files/figure-html/unnamed-chunk-6-1.png" width="504" style="display: block; margin: auto;" /> ??? Visualizamos las capas con la función `plot` --- .left-column[.center-left[<br> ```r ?plot.sf() ``` ]] .right-column[.center-right[ ```r plot(departamentos["departa"]) ``` <img src="index_files/figure-html/unnamed-chunk-8-1.png" width="504" style="display: block; margin: auto;" /> ]] ??? Si queremos sacar la leyenda? --- ```r plot(departamentos["departa"], key.pos = NULL) ``` <img src="index_files/figure-html/unnamed-chunk-9-1.png" width="504" style="display: block; margin: auto;" /> ??? Podemos cambiar el titulo --- ```r plot(departamentos["departa"], key.pos = NULL, main = "Departamentos") ``` <img src="index_files/figure-html/unnamed-chunk-10-1.png" width="504" style="display: block; margin: auto;" /> --- ## Ahora visualicemos `cuencas` ```r head(cuencas <- read_sf("datos/cuencas_cba", stringsAsFactors = TRUE), 2) ``` ``` ## Simple feature collection with 2 features and 6 fields ## geometry type: POLYGON ## dimension: XY ## bbox: xmin: 3622555 ymin: 6667466 xmax: 3701409 ymax: 6736392 ## epsg (SRID): NA ## proj4string: +proj=tmerc +lat_0=-90 +lon_0=-66 +k=1 +x_0=3500000 +y_0=0 +datum=WGS84 +units=m +no_defs ## # A tibble: 2 x 7 ## AREA PERIMETER COR3_ COR3_ID CUENCA SISTEMA geometry ## <dbl> <dbl> <dbl> <dbl> <fct> <fct> <POLYGON [m]> ## 1 2.94e9 337780. 2 28 SISTEMA~ SISTEMA~ ((3622555 6732250, 3623977 ~ ## 2 3.83e8 95968. 3 30 CUENCA ~ SISTEMA~ ((3633386 6733595, 3633582 ~ ``` --- ```r summary(cuencas) ``` ``` ## AREA PERIMETER COR3_ COR3_ID ## Min. : 96258450 Min. : 45776 Min. : 2.00 Min. : 1.00 ## 1st Qu.: 1513796750 1st Qu.: 326552 1st Qu.: 9.75 1st Qu.: 8.75 ## Median : 2828926500 Median : 427580 Median :17.50 Median :16.50 ## Mean : 5134409248 Mean : 492282 Mean :17.69 Mean :16.50 ## 3rd Qu.: 5330436500 3rd Qu.: 580937 3rd Qu.:25.25 3rd Qu.:24.25 ## Max. :53651410000 Max. :1666874 Max. :34.00 Max. :32.00 ## ## CUENCA ## CUENCA DE LAS SALINAS GRANDES : 2 ## CUENCA DE LA LAGUNA DE MAR CHIQUITA : 1 ## CUENCA DE LAS SALINAS DE AMBARGASTA : 1 ## CUENCA DE LOS ARROYOS ANCAS MAYO Y SAN MIGUEL: 1 ## CUENCA DE LOS RIOS CARNERO Y SALSIPUEDES : 1 ## CUENCA DE LOS RIOS JESUS MARIA Y PINTO : 1 ## (Other) :25 ## SISTEMA geometry ## SISTEMA CARCARANA : 1 POLYGON :32 ## SISTEMA GENERAL ROCA : 1 epsg:NA : 0 ## SISTEMA MORTEROS :12 +proj=tmer...: 0 ## SISTEMA RIO QUINTO : 4 ## SISTEMA SALINAS DE AMBARGASTA: 2 ## SISTEMA SALINAS GRANDES :11 ## SISTEMA SAN FRANCISCO : 1 ``` --- ```r plot(cuencas) ``` <img src="index_files/figure-html/unnamed-chunk-13-1.png" width="504" style="display: block; margin: auto;" /> --- .pull-left[ ```r plot(departamentos["departa"], main = NULL, col = "transparent") ``` <img src="index_files/figure-html/unnamed-chunk-14-1.png" width="504" style="display: block; margin: auto;" /> ] .pull-right[ ```r plot(cuencas["AREA"], main = NULL, col = "transparent") ``` <img src="index_files/figure-html/unnamed-chunk-15-1.png" width="504" style="display: block; margin: auto;" /> ] --- ## Si queremos ver superpuestas ambas capas? ```r plot(departamentos["departa"], col = "transparent", main = NULL, * reset = FALSE) plot(cuencas["AREA"], col = "transparent", add = TRUE) ``` <img src="index_files/figure-html/unnamed-chunk-16-1.png" width="504" style="display: block; margin: auto;" /> --- ```r st_crs(departamentos) ``` ``` ## Coordinate Reference System: ## EPSG: 4326 *## proj4string: "+proj=longlat +datum=WGS84 +no_defs" ``` ```r st_crs(cuencas) ``` ``` ## Coordinate Reference System: ## No EPSG code *## proj4string: "+proj=tmerc +lat_0=-90 +lon_0=-66 +k=1 +x_0=3500000 +y_0=0 +datum=WGS84 +units=m +no_defs" ``` ```r st_crs(departamentos) == st_crs(cuencas) ``` ``` ## [1] FALSE ``` --- ```r cuencas <- st_transform(cuencas, st_crs(departamentos)) st_crs(cuencas) ``` ``` ## Coordinate Reference System: ## EPSG: 4326 *## proj4string: "+proj=longlat +datum=WGS84 +no_defs" ``` ```r st_crs(departamentos) == st_crs(cuencas) ``` ``` ## [1] TRUE ``` --- ```r head(cuencas,4) ``` ``` ## Simple feature collection with 4 features and 6 fields ## geometry type: POLYGON ## dimension: XY ## bbox: xmin: -65.45996 ymin: -30.73717 xmax: -63.92005 ymax: -29.49721 *## epsg (SRID): 4326 *## proj4string: +proj=longlat +datum=WGS84 +no_defs ## # A tibble: 4 x 7 ## AREA PERIMETER COR3_ COR3_ID CUENCA SISTEMA geometry ## <dbl> <dbl> <dbl> <dbl> <fct> <fct> <POLYGON [°]> ## 1 2.94e9 337780. 2 28 SISTEMA~ SISTEMA~ ((-64.73567 -29.53934, -64.~ ## 2 3.83e8 95968. 3 30 CUENCA ~ SISTEMA~ ((-64.62412 -29.5261, -64.6~ ## 3 2.70e9 454788. 4 27 CUENCA ~ SISTEMA~ ((-64.83056 -29.55093, -64.~ ## 4 2.72e9 391502. 5 31 CUENCA ~ SISTEMA~ ((-64.83056 -29.55093, -64.~ ``` --- ```r plot(departamentos["departa"], col = "transparent", main = NULL, reset = FALSE) plot(cuencas["AREA"], col = "transparent", add = TRUE) ``` <img src="index_files/figure-html/unnamed-chunk-23-1.png" width="504" style="display: block; margin: auto;" /> --- ```r plot(departamentos["departa"], col = "transparent", main = NULL, reset = FALSE) plot(cuencas["AREA"], add = TRUE, col = "transparent", border = "red") ``` <img src="index_files/figure-html/unnamed-chunk-24-1.png" width="504" style="display: block; margin: auto;" /> --- ```r plot(departamentos["departa"], col = "transparent", main = NULL, reset = FALSE) plot(cuencas["AREA"], add = TRUE, col = "transparent", border = "red") legend("bottomright", legend = c("Límites departamentales", "Cuencas"), col = c("black", "red"), lty = 1, lwd = 3) ``` <img src="index_files/figure-html/unnamed-chunk-25-1.png" width="504" style="display: block; margin: auto;" /> --- ```r plot(departamentos["departa"], col = "transparent", main = NULL, reset = FALSE) plot(cuencas["AREA"], add = TRUE, col = "transparent", border = "red") legend("bottomright", legend = c("Límites departamentales", "Cuencas"), col = c("black", "red"), lty = 1, lwd = 3) prettymapr::addnortharrow() ``` <img src="index_files/figure-html/unnamed-chunk-26-1.png" width="504" style="display: block; margin: auto;" /> --- ```r plot(departamentos["departa"], col = "transparent", main = NULL, reset = FALSE) plot(cuencas["AREA"], add = TRUE, col = "transparent", border = "red") legend("bottomright", legend = c("Límites departamentales", "Cuencas"), col = c("black", "red"), lty = 1, lwd = 3) prettymapr::addnortharrow() prettymapr::addscalebar() ``` ``` ## Autodetect projection: assuming lat/lon (epsg 4326) ``` ``` ## Scale on map varies by more than 5%, scalebar may be inaccurate ``` --- <img src="index_files/figure-html/unnamed-chunk-27-1.png" width="504" style="display: block; margin: auto;" /> --- ```r prettymap(plot(departamentos["departa"], col = "transparent", main = "Departamentos"), drawarrow=TRUE) ``` ``` ## Audotdetect projection: assuming Google Mercator (epsg 3857) ``` --- .left-column[ La escala está en centímetros! .center[
] ] .right-column[ <img src="index_files/figure-html/unnamed-chunk-28-1.png" width="504" style="display: block; margin: auto;" /> ] --- ```r prettymap(plot(departamentos["departa"], col = "transparent", main = "Departamentos"), drawarrow=TRUE, * scale.plotepsg = 4326) ``` --- .left-column[ .center[
] ] .right-column[ <img src="index_files/figure-html/unnamed-chunk-29-1.png" width="504" style="display: block; margin: auto;" /> ] --- # Mapa de fondo ```r bordes <- st_bbox(cuencas) names(bordes) <- c("left", "bottom", "right", "top") ``` ```r Mapa <- get_stamenmap(bbox = bordes, zoom = 2) ``` ```r try(plot(cuencas["AREA"], axes = TRUE, bgMap= Mapa)) ``` --- ```r cuencas <- st_transform(cuencas, crs = st_crs(3857)) plot(cuencas["AREA"], axes = TRUE, bgMap= Mapa) ``` --- <img src="index_files/figure-html/unnamed-chunk-31-1.png" width="504" style="display: block; margin: auto;" /> --- # Lectura de archivo de texto ```r head(muestreo <- read.table("datos/MuestreoSuelo.txt", header = T, sep = "\t"),8) ``` ``` ## Xt Yt Limo CC K ## 1 603163.6 6576899 67.0 29.3 2.30 ## 2 596537.1 6390518 66.0 28.9 2.02 ## 3 595665.5 6380484 62.9 27.5 1.38 ## 4 601138.5 6353446 57.4 25.4 1.60 ## 5 601798.1 6344096 61.1 25.3 1.36 ## 6 587501.2 6615272 65.3 25.4 2.40 ## 7 589808.2 6593001 62.6 25.7 2.30 ## 8 585406.5 6575712 69.3 23.4 1.81 ``` --- ```r head(muestreo <- st_as_sf(muestreo, coords = c("Xt", "Yt"), crs = 32720), 5) ``` ``` ## Simple feature collection with 5 features and 3 fields ## geometry type: POINT ## dimension: XY ## bbox: xmin: 595665.5 ymin: 6344096 xmax: 603163.6 ymax: 6576899 ## epsg (SRID): 32720 ## proj4string: +proj=utm +zone=20 +south +datum=WGS84 +units=m +no_defs ## Limo CC K geometry ## 1 67.0 29.3 2.30 POINT (603163.6 6576899) ## 2 66.0 28.9 2.02 POINT (596537.1 6390518) ## 3 62.9 27.5 1.38 POINT (595665.5 6380484) ## 4 57.4 25.4 1.60 POINT (601138.5 6353446) ## 5 61.1 25.3 1.36 POINT (601798.1 6344096) ``` --- ```r muestreoLatLong <- st_transform(muestreo, st_crs(departamentos)) plot(departamentos["departa"], col = "transparent", reset = FALSE) plot(muestreoLatLong["Limo"], add = TRUE) ``` <img src="index_files/figure-html/unnamed-chunk-34-1.png" width="504" style="display: block; margin: auto;" /> --- ```r summary(muestreo) ``` ``` ## Limo CC K geometry ## Min. : 0.00 Min. : 5.00 Min. :0.400 POINT :355 ## 1st Qu.:24.60 1st Qu.:13.10 1st Qu.:1.500 epsg:32720 : 0 ## Median :40.00 Median :17.70 Median :1.810 +proj=utm ...: 0 ## Mean :39.59 Mean :17.72 Mean :1.856 ## 3rd Qu.:55.90 3rd Qu.:21.90 3rd Qu.:2.240 ## Max. :89.10 Max. :34.00 Max. :4.800 ## NA's :2 NA's :2 NA's :2 ``` --- ```r plot(muestreo, pch = 18 , cex = 3) ``` <img src="index_files/figure-html/unnamed-chunk-36-1.png" width="936" style="display: block; margin: auto;" /> --- # Librería `ggplot2` Idividualmente se especifican partes del gráfico. Luego estas partes se combinan para obtener el gráfico completo. Estas partes son: - Datos - Mapeo estético (*aesthetic mapping*) - Objetos geométricos (*geometric object*) -- - Transformaciones estadísticas (*statistical transformations*) - Escalas (*scales*) - Sistema de coordenadas (*coordinate system*) - Ajustes de posición (*position adjustments*) - Particiones (*faceting*) --- .pull-left[ ```r ggplot(cuencas) + geom_sf() ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-37-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r ggCuencasMuestero <- ggplot() + geom_sf(data = cuencas) + geom_sf(data = muestreo, aes( color = Limo), size = 3) ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-38-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r *ggCuencasMuestero + scale_color_continuous(na.value = "red") ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-39-1.png" width="504" style="display: block; margin: auto;" /> ] --- # Cuantos puntosde muestreo hay en cada cuenca???
```r st_covers(cuencas, muestreoLatLong) ``` <div class="alert alert-danger" style="background-color:#ffb3b3"> <strong>Error</strong> in st_geos_binop("covers", x, y, sparse = sparse, prepared = prepared): st_crs(x) == st_crs(y) is not TRUE </div> ```r cuencasUTM <- st_transform(cuencas, st_crs(muestreo)) lengths(st_covers(cuencasUTM, muestreo)) ``` ``` ## [1] 6 1 5 0 1 2 11 2 6 1 0 4 5 5 6 4 1 6 8 ## [20] 8 0 18 14 34 2 129 4 13 14 9 16 17 ``` --- ```r st_area(cuencas) ``` ``` ## Units: [m^2] ## [1] 3912388561 507717498 3623134078 3640064357 310557789 1581332179 ## [7] 5554999642 5786807918 2490683391 2134558806 6919666862 2315274992 ## [13] 2431527912 1784949712 4437412622 3435445941 1587993053 3085770440 ## [19] 4089861556 5174023817 130677022 10741440223 9630000798 21801299580 ## [25] 970198380 76086539793 1566604607 8570203169 9268393829 5343655868 ## [31] 9858442680 10990036885 ``` ```r lengths(st_covers(cuencasUTM, muestreo))/st_area(cuencasUTM) ``` ``` ## Units: [1/m^2] ## [1] 0.0000000020431392 0.0000000026148004 0.0000000018519580 0.0000000000000000 ## [5] 0.0000000042822751 0.0000000016868273 0.0000000026571370 0.0000000004638433 ## [9] 0.0000000032495556 0.0000000006326527 0.0000000000000000 0.0000000023337350 ## [13] 0.0000000028004203 0.0000000038085260 0.0000000018513786 0.0000000015868747 ## [17] 0.0000000008574153 0.0000000026367409 0.0000000026645968 0.0000000021166040 ## [21] 0.0000000000000000 0.0000000023025389 0.0000000020056198 0.0000000021564699 ## [25] 0.0000000028389907 0.0000000024100838 0.0000000035699660 0.0000000021858622 ## [29] 0.0000000021923332 0.0000000024691772 0.0000000023950658 0.0000000022937989 ``` --- ```r puntosKm <- lengths(st_covers(cuencasUTM, muestreo))/units::set_units(st_area(cuencasUTM), km^2) cuencasUTM$CantidadMuestrasKm <- puntosKm cuencasUTM$CantidadMuestrasKm ``` ``` ## Units: [1/km^2] ## [1] 0.0020431392 0.0026148004 0.0018519580 0.0000000000 0.0042822751 ## [6] 0.0016868273 0.0026571370 0.0004638433 0.0032495556 0.0006326527 ## [11] 0.0000000000 0.0023337350 0.0028004203 0.0038085260 0.0018513786 ## [16] 0.0015868747 0.0008574153 0.0026367409 0.0026645968 0.0021166040 ## [21] 0.0000000000 0.0023025389 0.0020056198 0.0021564699 0.0028389907 ## [26] 0.0024100838 0.0035699660 0.0021858622 0.0021923332 0.0024691772 ## [31] 0.0023950658 0.0022937989 ``` --- ```r plot(cuencasUTM["CantidadMuestrasKm"]) ``` <img src="index_files/figure-html/unnamed-chunk-44-1.png" width="504" style="display: block; margin: auto;" /> --- ```r st_covers(cuencasUTM,muestreo) ``` ``` ## Sparse geometry binary predicate list of length 32, where the predicate was `covers' ## first 10 elements: ## 1: 197, 227, 228, 229, 257, 258 ## 2: 256 ## 3: 231, 259, 286, 287, 288 ## 4: (empty) ## 5: 167 ## 6: 110, 137 ## 7: 111, 138, 139, 140, 168, 169, 170, 198, 199, 200, ... ## 8: 88, 89 ## 9: 260, 261, 289, 290, 306, 307 ## 10: 308 ``` --- ```r mediaCC <- sapply(st_covers(cuencasUTM,muestreo), function(x) { mean(muestreo[x,][["CC"]], na.rm = TRUE) }) mediaCC ``` ``` *## [1] 20.36667 15.60000 16.42000 NaN 19.30000 22.60000 20.33333 21.10000 *## [9] 17.61667 10.20000 NaN 19.22500 25.78000 15.46000 17.50000 18.72500 *## [17] 16.00000 22.65000 19.48750 21.17500 NaN 21.16667 13.45714 21.45882 ## [25] 31.40000 18.26899 13.27500 15.16154 10.99286 16.94444 13.20625 9.70000 ``` --- .pull-left[ ```r cuencasUTM$MediaCC <- mediaCC ggplot(cuencasUTM) + geom_sf(aes(fill = MediaCC)) ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-47-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r ggplot(cuencasUTM) + geom_sf(aes(fill = MediaCC)) + labs(fill = "Media C.C.") ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-48-1.png" width="504" style="display: block; margin: auto;" /> ] --- ```r tm_shape(cuencasUTM) + tm_fill() ``` <img src="index_files/figure-html/unnamed-chunk-49-1.png" width="504" style="display: block; margin: auto;" /> --- # Paquete `tmap` - La sintaxis es similar a `ggplot2`, pero orientada a mapas - La mayoría de las funciones comienzan con `tmap_` - Para comenzar a graficar, es necesario especificarlo con `tm_shape` - Las capas se agregan mediante `+` - Permite graficar mapas estáticos o interactivos con el mismo código `tmap_mode()`. --- .pull-left[ ```r tm_shape(cuencasUTM) + tm_fill("MediaCC") + tm_borders() ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-50-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", style = "quantile") + tm_borders() + tm_basemap() ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-51-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r tmap_mode("view") ``` ``` ## tmap mode set to interactive viewing ``` ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", style = "quantile") + tm_borders() + tm_basemap() ``` ] .pull-right[
] --- .pull-left[ ```r tmap_mode("view") ``` ``` ## tmap mode set to interactive viewing ``` ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", style = "quantile") + tm_borders() + tm_basemap() + * tm_view(alpha = 1, basemaps = "Esri.WorldTopoMap") ``` ] .pull-right[
] --- .pull-left[ ```r tmap_mode("plot") ``` ``` ## tmap mode set to plotting ``` ```r tm_shape(cuencasUTM) + tm_fill("MediaCC") + tm_borders() + tm_basemap() + tm_symbols(size = "AREA", shape = tmap_icons("https://png.pngtree.com/svg/20160627/area_1270351.png")) ``` ``` ## The legend is too narrow to place all symbol sizes. ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-54-1.png" width="504" style="display: block; margin: auto;" /> ] --- .pull-left[ ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn") + tm_borders() + tm_basemap() + tm_symbols(size = "AREA") + tm_scale_bar() + tm_layout(legend.format = list(text.separator= " a ", text.align = "center")) ``` ] .pull-right[ <img src="index_files/figure-html/unnamed-chunk-55-1.png" width="504" style="display: block; margin: auto;" /> ] --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC") + tm_borders() + tm_basemap() + tm_symbols(size = "AREA", col="blue", title.size = "Area") + tm_scale_bar() + tm_compass(position = c( "right", "top")) ``` <img src="index_files/figure-html/unnamed-chunk-56-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC") + tm_borders() + tm_basemap() + tm_symbols(size = "AREA", col="blue", title.size = "Area") + tm_scale_bar() + tm_compass(position = c( "right", "top")) + tm_legend( text.size=1, title.size=1.2, legend.outside=TRUE, frame="gray50", height=.6) ``` ``` ## Legend labels were too wide. Therefore, legend.text.size has been set to 0.86. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger. ``` <img src="index_files/figure-html/unnamed-chunk-57-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC") + tm_borders() + tm_basemap() + tm_symbols(size = "AREA", col="blue", title.size = "Area") + tm_scale_bar() + tm_compass(position = c( "right", "top")) + tm_facets("SISTEMA",nrow = 1) ``` <img src="index_files/figure-html/unnamed-chunk-58-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC", style = "quantile") + tm_borders() + tm_symbols(size = "AREA", col="blue", title.size = "Area") + tm_facets("SISTEMA") + tm_scale_bar() + tm_compass(position = c( "right", "top")) ``` <img src="index_files/figure-html/unnamed-chunk-59-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC", style = "quantile") + tm_borders() + tm_symbols(size = "AREA", col="blue", title.size = "Area") + tm_facets("SISTEMA") + tm_scale_bar() + tm_compass(position = c( "right", "top")) + tm_layout(legend.format = list(text.separator= " a ", text.align = "left")) ``` <img src="index_files/figure-html/unnamed-chunk-60-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", palette="RdYlGn", title.size = "Media CC", style = "cont", textNA="Sin Muestras") + tm_borders() + tm_facets("SISTEMA") + tm_scale_bar(text.size = 10) + tm_compass(type = "rose", position = c( "right", "top"), size = 2) ``` <img src="index_files/figure-html/unnamed-chunk-61-1.png" width="504" style="display: block; margin: auto;" /> --- .pull-left[ ```r tmap_cuencas <- tm_shape(cuencasUTM) + tm_fill("MediaCC", style = "quantile") + tm_borders() + tm_basemap() + tm_view(alpha = 1, basemaps = "Esri.WorldTopoMap") ``` ] .pull-right[ ```r tmap_muestreo <- tm_shape(muestreo) + tm_bubbles(col = "K", style = "cont", textNA = "Sin dato") + tm_basemap() ``` ] --- ```r tmap_arrange(tmap_cuencas, tmap_muestreo) ``` <img src="index_files/figure-html/unnamed-chunk-64-1.png" width="504" style="display: block; margin: auto;" /> --- ```r tm_shape(cuencasUTM) + tm_fill("MediaCC", style = "quantile") + tm_borders() + tm_basemap() + tm_shape(muestreo) + tm_bubbles(col = "K", style = "cont") + tm_basemap() ``` <img src="index_files/figure-html/unnamed-chunk-65-1.png" width="504" style="display: block; margin: auto;" /> --- ```r leaflet() %>% addTiles() %>% addCircles(data = muestreoLatLong) %>% addMiniMap(position = "topleft" , width = 150, height = 150) ```
--- ```r leaflet() %>% addTiles() %>% addCircles(data = muestreoLatLong) %>% addMiniMap(position = "topleft" , width = 150, height = 150) %>% addLogo("https://media.giphy.com/media/l1LcbeAkRm2UrdNio/giphy.gif", position = "bottomleft",offset.x = 5, offset.y = 100, width = 480, height = 270) ```
--- # Referencias .small[ Bivand, R. and A. Gebhardt (2000). "Implementing Functions for Spatial Statistical Analysis Using the Language". In: _Journal of Geographical Systems_ 2.3, pp. 307-317. Pebesma, E. (2018). "Simple Features for R: Standardized Support for Spatial Vector Data". In: _The R Journal_ 10.1, pp. 439-446. URL: [https://journal.r-project.org/archive/2018/RJ-2018-009/index.html](https://journal.r-project.org/archive/2018/RJ-2018-009/index.html). R Core Team (2019). _R: A Language and Environment for Statistical Computing_. R Foundation for Statistical Computing. Vienna, Austria. URL: [https://www.R-project.org/](https://www.R-project.org/). RStudio Team (2016). _RStudio: Integrated Development Environment for R_. RStudio, Inc.. Boston, MA. URL: [http://www.rstudio.com/](http://www.rstudio.com/). ]